<template>
    <div class="vote" v-if="packetVote">
        <page-title :title="packetVote.title"></page-title>
        <swiper v-if="packetVote.content && packetVote.content.voteRelatedImg" :aspect-ratio="1/4" :show-dots="false" loop auto class="cl-swiper">
            <img :src="packetVote.content.voteRelatedImg">
        </swiper>
        <article class="article">
            <div class="dt-header">
                <h2>{{packetVote.title}}</h2>
                <p class="dt-info">
                    <span class="date">
                        <span>{{packetVote.create_time}}</span>
                    </span>
                </p>
            </div>
            <div class="rich-ctx" style="margin-bottom:1rem;" v-html="packetVote.rich_ctx">
            </div>
            <p class="time">投票时间截止时间：
                <span>{{end_time}}</span>
            </p>
            <p v-if="nowDate > +new Date(end_time)" class="count-down count-down-end">
                活动已经结束，欢迎下次参加！
            </p>
            <p v-else class="count-down">
                <span> 距离活动结束时间：</span>
                <clocker :time="+new Date(end_time)"></clocker>
            </p>
        </article>
        <div class="wrap">
            <div v-if="nowDate < +new Date(end_time)" class="vote-box" v-for="(item,index) in vote" :key="index">
                <p class="vb-title">
                    <b>{{index+1 +'. '}}</b>{{item.title}}</p>
                <div v-if="item.image" class="vb-img" :style="{backgroundImage:'url('+item.image+')'}">
                    <!-- <img :src="item.imgUrl" alt=""> -->
                </div>
                <p v-if="item.description" class="vb-desc">简介：{{item.description}}</p>
                <div class="vb-result">
                    <span v-if="voteTotal!=0" class="vb-result-percent">{{((item.count/voteTotal)*100).toFixed(2)}}%</span>
                    <span v-else class="vb-result-percent">0%</span>
                    <x-progress v-if="voteTotal!=0" :percent="parseInt(((item.count/voteTotal)*100).toFixed(2))" :show-cancel="false"></x-progress>
                    <x-progress v-else :percent="0" :show-cancel="false"></x-progress>
                    <x-button mini type="primary" v-if="item.state&&repeat==0" disabled>已投票</x-button>
                    <x-button mini type="primary" @click.native="voteCount(item,index)" v-else>投Ta一票</x-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { getVoteById, getOneVoteByDatasIdAndVoteId, findDatasAllByVoteId, saveVoteReceipt, getReceiptByParams } from '@/api/community';
import { getPacketById } from '@/api/packet';
import { getEnterpriseInfo } from "@/api/enterprise"
import { Swiper, Clocker, XButton, XProgress } from 'vux'
export default {
    data() {
        return {
            receiptId: null,
            voteId: this.$route.query.id,
            eid: this.$route.query.eid,
            activityId: null,
            //分享者ID
            shareUserId: this.$route.query.shareUserId,
            // 总投票数
            voteTotal: 0,
            nowDate: +new Date(),
            // 微信只能支持 yyyy/mm/dd hh:mm:ss
            end_time: null,
            vote: [],
            datas: [],
            //判断是否可以重复投票(1 可以 0 不可以)
            repeat: null,
            //资料包名称
            packetVote: null,
        }
    },
    components: {
        Swiper,
        Clocker,
        XButton,
        XProgress
    },
    mounted() {

    },
    methods: {
        // 投票统计
        voteCount(item, index) {
            //先清空里面的数据
            this.datas = []
            var This = this
            item.count++
            this.voteTotal++
            if (this.repeat == 0) {
                // item.state == true
                // console.log(item.state)
                this.$set(this.vote[index], 'state', true)
            }
            saveVoteReceipt(This.eid, This.voteId, JSON.stringify(This.vote), item.id, this.activityId).then(res => {
                // 投票成功显示文字
                this.$vux.toast.text('投票成功', 'middle')
            }).catch(_ => {
                this.$vux.toast.text('投票失败', 'middle')
            })

        },
        // callback() {

        // }
    },
    created() {
        getVoteById(this.voteId).then(res => {
            if (res.vote.end_time) {
                res.vote.end_time = res.vote.end_time.replace(/-/g, '/')
            }
            this.end_time = res.vote.end_time
            this.activityId = res.vote.activity_id
            this.repeat = res.vote.repeat
            //根据id查询资料包
            getPacketById(res.vote.packet_id).then(async resp => {
                //得到多个投票项
                resp.packet.content = JSON.parse(resp.packet.content)
                this.packetVote = resp.packet
                //获取单个投票的总数
                await getOneVoteByDatasIdAndVoteId(this.voteId, JSON.stringify(resp.packet.content.vote.map(item => item.id))).then(resc => {
                    if (resc.result) {
                        resc.result.forEach(function (ele, i) {
                            if (resp.packet.content.vote[i].id == ele.id) {
                                //将单个投票的总数赋值
                                resp.packet.content.vote[i].count = ele.oneVoteCount
                            }
                        }, this);
                    }
                    //判断是否可以重复投票(1.可以 0.不可以)
                    if (res.resultList.length > 0 && res.vote.repeat == 0) {
                        res.resultList.forEach(function (ele, i) {
                            if (resp.packet.content.vote[i].id == ele.id) {
                                //将后台得到的状态赋值（true：已投票   false:未投票）
                                resp.packet.content.vote[i].state = ele.state
                            }
                        }, this);
                    } else {
                        resp.packet.content.vote.forEach(function (ele, i) {
                            resp.packet.content.vote[i].state = false
                        })
                    }
                    //将得到的最终结果赋值
                    // this.vote = resp.packet.content.vote
                    // this.receiptId = this.vote.id
                }).catch(_ => {
                    console.log("获取单个投票总数报错")
                })
                // 判断用户是否投过票
                getReceiptByParams(this.eid, this.voteId, this.activityId).then(resb => {
                    if (resb.resultList.length > 0) {
                        resb.resultList.forEach(function (ele, i) {
                            if (resp.packet.content.vote[i].id == ele.id) {
                                //将后台得到的状态赋值（true：已投票   false:未投票）
                                resp.packet.content.vote[i].state = ele.state
                            }
                        }, this);
                    } else {
                        resp.packet.content.vote.forEach(function (ele, i) {
                            resp.packet.content.vote[i].state = false
                            resp.packet.content.vote[i].totalVote = 0
                        })
                    }
                    //将得到的最终结果赋值
                    this.vote = resp.packet.content.vote
                    this.receiptId = this.vote.id
                }).catch(_ => {
                    console.log("判断用户是否投票报错")
                })
                //转发分享
                let share_thumburl = resp.packet.share_thumburl
                if (!share_thumburl) {
                    await getEnterpriseInfo().then(resc => {
                        share_thumburl = resc.enterprise.logo_1x1
                    });
                }
                // 获取微信分享参数
                // this.wxShare(this.voteId, this.shareUserId, resp.packet.share_title ? resp.packet.share_title : res.vote.name,
                //     resp.packet.share_remarks ? resp.packet.share_remarks : res.vote.name, share_thumburl,
                //     (type) => {
                //         this.$vux.toast.text('分享成功')
                //     }, 6)
            }).catch(_ => {
                console.log("查询资料包报错")
            })
        }).catch(_ => {
            console.log("查询投票报错")
        })
        //根据投票id获取所有投票的总数
        findDatasAllByVoteId(this.voteId).then(res => {
            this.voteTotal = res.count
        }).catch(_ => {
            console.log("获取所有投票总数报错")
        })
    }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
